package com.liangxy.news.ui.auth;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.liangxy.news.R;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.model.User;
import com.liangxy.news.ui.main.MainActivity;
import com.liangxy.news.util.SharedPreferencesManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Login activity for user authentication
 */
public class LoginActivity extends AppCompatActivity {
    
    private static final String TAG = "LoginActivity";
    
    private EditText etPhoneNumber;
    private EditText etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private TextView tvForgotPassword;
    private ProgressBar progressBar;
    
    private SharedPreferencesManager preferencesManager;
    private ExecutorService executorService;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        // Initialize components
        etPhoneNumber = findViewById(R.id.etPhoneNumber);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tvRegister);
        tvForgotPassword = findViewById(R.id.tvForgotPassword);
        progressBar = findViewById(R.id.progressBar);
        
        preferencesManager = new SharedPreferencesManager(this);
        executorService = Executors.newSingleThreadExecutor();
        
        // 检查是否已经登录
        if (preferencesManager.isLoggedIn()) {
            Log.d(TAG, "User already logged in, navigating to main activity");
            navigateToMain();
            return;
        }
        
        // Set click listeners
        btnLogin.setOnClickListener(v -> loginUser());
        tvRegister.setOnClickListener(v -> navigateToRegister());
        tvForgotPassword.setOnClickListener(v -> navigateToForgotPassword());
    }
    
    /**
     * Login user with provided credentials
     */
    private void loginUser() {
        String phoneNumber = etPhoneNumber.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        
        // Validate input
        if (TextUtils.isEmpty(phoneNumber)) {
            etPhoneNumber.setError("请输入手机号");
            return;
        }
        
        if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            return;
        }
        
        // Show progress
        progressBar.setVisibility(View.VISIBLE);
        
        // Check credentials in database
        executorService.execute(() -> {
            try {
                AppDatabase database = AppDatabase.getInstance(getApplicationContext());
                User user = database.userDao().getUserByPhoneNumber(phoneNumber);
                
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    
                    if (user != null && password.equals(user.getPassword())) {
                        // Login successful
                        Log.d(TAG, "Login successful for user: " + user.getUsername());
                        
                        // 确保用户数据保存到SharedPreferences
                        preferencesManager.saveUser(user);
                        
                        // Update last login time
                        executorService.execute(() -> {
                            try {
                                user.setLastLoginTime(System.currentTimeMillis());
                                database.userDao().update(user);
                                Log.d(TAG, "Updated last login time for user: " + user.getId());
                            } catch (Exception e) {
                                Log.e(TAG, "Error updating last login time", e);
                            }
                        });
                        
                        Toast.makeText(LoginActivity.this, R.string.login_success, Toast.LENGTH_SHORT).show();
                        navigateToMain();
                    } else {
                        // Login failed
                        Log.d(TAG, "Login failed: Invalid credentials");
                        Toast.makeText(LoginActivity.this, "手机号或密码错误", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "Error during login", e);
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(LoginActivity.this, "登录时发生错误，请重试", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    /**
     * Navigate to register screen
     */
    private void navigateToRegister() {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }
    
    /**
     * Navigate to forgot password screen
     */
    private void navigateToForgotPassword() {
        Intent intent = new Intent(this, ForgotPasswordActivity.class);
        startActivity(intent);
    }
    
    /**
     * Navigate to main screen
     */
    private void navigateToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executorService != null) {
            executorService.shutdown();
        }
    }
} 